#!/usr/bin/env python
# encoding: utf-8
"""
    @author:水痕
    @time:2018-09-04 17:38:26
    @email:332904234@qq.com
    @version:1.0
    @fileName:new_article.py
    @describe:
"""

from django.shortcuts import render
from django.views.generic import View
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

from article import models
from article.forms import ArticleForms
from django.conf import settings

from qiniu import Auth

from django.contrib.auth import get_user_model

# 从系统中获取自己定义的user表
User = get_user_model()


@method_decorator(login_required, name='dispatch')
class NewArticle(View):
    """
    新增博客视图类
    """

    def get(self, request, *args, **kwargs):
        # 获取文章的类别
        category_list = models.BlogCategoryModel.objects.all()
        type_list = models.TypeCategoryModel.objects.all()
        return render(request, 'new-article.html', locals())

    def post(self, request, *args, **kwargs):
        article_form = ArticleForms(request.POST)
        if article_form.is_valid():
            try:
                title = article_form.cleaned_data.get('title', None)
                content = article_form.cleaned_data.get('content', None)
                category = article_form.cleaned_data.get('category', None)
                type = article_form.cleaned_data.get('type', None)
                author = User.objects.filter(username=request.user).first()
                models.ArticleModel.objects.create(title=title, content=content, category_id=category, type_id=type,
                                                   author=author)
                return JsonResponse({'code': 0, 'message': '成功'})
            except Exception as e:
                print(e)
                return JsonResponse({'code': 1, 'message': e})
        else:
            message = article_form.errors
            return JsonResponse({'code': 1, 'message': message})


class QiNiuToken(View):
    """
    定义一个获取七牛token的视图
    """

    def get(self, request, *args, **kwargs):
        # 获取认证
        q = Auth(settings.ACCESS_KEY_QI_NIU, settings.SECRET_KEY_QI_NIU)
        # 设置空间
        bucket_name = 'test'

        # 获取token
        token = q.upload_token(bucket_name)
        return JsonResponse({'uptoken': token, 'resultCode': 0})
